#!/usr/bin/env bash

# EMS Web 前端热更新调试脚本
# 作用：快捷启动 Vite 开发服务器，支持热更新调试

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
WEB_DIR="$PROJECT_ROOT/web/frontend"

HOST="${DEV_HOST:-0.0.0.0}"
PORT="${DEV_PORT:-5173}"

CYAN='\033[0;36m'
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

log() {
  echo -e "${CYAN}[dev]${NC} $1"
}

log_success() {
  echo -e "${GREEN}[ok]${NC} $1"
}

log_error() {
  echo -e "${RED}[err]${NC} $1" >&2
}

require_command() {
  if ! command -v "$1" >/dev/null 2>&1; then
    log_error "未找到命令: $1"
    exit 1
  fi
}

check_node_version() {
  local version_major
  version_major=$(node --version | sed 's/^v//' | cut -d'.' -f1)
  if [[ "$version_major" -lt 16 ]]; then
    log_error "Node.js 版本过低 (当前: $(node --version))，请升级到 16+"
    exit 1
  fi
}

ensure_dependencies() {
  cd "$WEB_DIR"

  if [[ ! -d node_modules ]]; then
    log "检测到首次运行，执行 npm install ..."
    npm install
    log_success "依赖安装完成"
    return
  fi

  if [[ "$WEB_DIR/package-lock.json" -nt "$WEB_DIR/node_modules" ]]; then
    log "锁文件更新，执行 npm install ..."
    npm install
    log_success "依赖已更新"
  fi
}

start_dev_server() {
  cd "$WEB_DIR"
  log "启动 Vite 开发服务 (host=$HOST port=$PORT) ..."
  log "可通过环境变量 DEV_HOST / DEV_PORT 调整"
  npm run dev -- --host "$HOST" --port "$PORT"
}

main() {
  require_command node
  require_command npm
  check_node_version
  ensure_dependencies
  start_dev_server
}

main "$@"
